import cv2 as cv
import numpy as np


def main():
    filePath = '../data/multObj.png'
    img = cv.imread(filePath)
    imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    thresh, maxValue = 127, 255
    threshType = cv.THRESH_BINARY
    ret, thresh_img = cv.threshold(imgGray, thresh, maxValue, threshType)

    retrievalMode = cv.RETR_TREE
    approxMethod = cv.CHAIN_APPROX_NONE
    contours, hierarchy = cv.findContours(thresh_img, retrievalMode, approxMethod)

    SymbolPerimeter = 160
    offset = round(SymbolPerimeter * 0.2)
    validIdx = []

    for idx, cnt in enumerate(contours):
        perimeter = cv.arcLength(cnt, True)
        print(idx, ":", cnt.size, ",", perimeter)
        minP, maxP = SymbolPerimeter - offset, SymbolPerimeter + offset
        if minP < perimeter < maxP:
            validIdx.append(idx)

    imgBackGround = np.zeros(img.shape, np.uint8)
    for idx in validIdx:
        cv.drawContours(imgBackGround, contours, idx, (0, 0, 255), 1)

    cv.imshow("img", img)
    cv.imshow("imgBG", imgBackGround)
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == "__main__":
    main()
